﻿# -*- coding: utf-8 -*-
import os

import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import Font, Alignment, Border, Side, NamedStyle
from wcwidth import wcswidth
import sys
import shutil
import io

# 修改标准输出的编码
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

# 记录日志 a模式代表追加写入 # with open('python_log.txt', 'a', encoding='utf-8') as file:
def write_log(content):
    # with open('python_script/python_log.txt', 'a', encoding='utf-8') as file:
    with open('python_log.txt', 'a', encoding='utf-8') as file:
        file.write(f"{content}\n")


def create_excels(excels_dir, each_chunk):
    # 获取全部的excel
    excels = os.listdir(excels_dir)
    # 按照文件名序号从小到大排序
    sorted_files = sorted(excels, key=file_number)
    # 每份 n 个，分成若干个
    chunked_list = split_list(sorted_files, each_chunk)
    # 把数据写进去
    for i, child_list in enumerate(chunked_list):
        start_num = file_number(child_list[0])  # 获取列表第一个元素
        end_num = file_number(child_list[-1])  # 获取列表最后一个元素
        s_name = f"档号【{start_num}~{end_num}】"
        if i == 0:
            # 创建一个空文件
            df = pd.DataFrame()
            df.to_excel(f"{excels_dir}.xlsx", sheet_name=s_name, index=False)
        concat_excels(excels_dir, child_list, s_name)
    # 设置样式
    set_cell_style(f"{excels_dir}.xlsx")

    return f"{excels_dir}.xlsx"


# 把数字文件名提取出来，成数字，从小到大排序
def file_number(excel):
    file_info = os.path.splitext(excel)  # 返回一个元组如 ('1', '.xlsx')
    filename = int(file_info[0])  # 转化为纯数字
    return filename


# 例如把 1000 个案卷，每份200个分成 5部分
def split_list(lst, size):
    return [lst[i:i + size] for i in range(0, len(lst), size)]


def concat_excels(excels_dir, excels, s_name):
    all_con = []
    for j, excel in enumerate(excels):
        df = pd.read_excel(f"{excels_dir}/{excel}", header=None)
        all_con.append(df)
    # 把数据写入到文件
    with pd.ExcelWriter(f"{excels_dir}.xlsx", mode='a', if_sheet_exists='overlay') as writer:
        concat_data = pd.concat(all_con)
        concat_data.to_excel(writer, sheet_name=s_name, index=False, header=False)


# 对工作表进行样式设置 29号文格式
def set_cell_style(result_excel):
    wb = load_workbook(result_excel)

    # 卷内目录样式
    page_row1_style = NamedStyle(name='page_row1_style')
    page_row1_style.font = Font(name='宋体', size='22', bold=True)
    page_row1_style.alignment = Alignment(horizontal='center', vertical='center')

    # 档号样式
    page_row2_style = NamedStyle(name='page_row2_style')
    page_row2_style.font = Font(name='宋体', size='12')
    page_row2_style.alignment = Alignment(horizontal='right', vertical='center')

    # 属性样式
    page_row3_style = NamedStyle(name='page_row3_style')
    page_row3_style.font = Font(name='宋体', size='12', bold=True)
    page_row3_style.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    page_row3_style.border = Border(left=Side(border_style='thin'), top=Side(border_style='thin'),
                                    right=Side(border_style='thin'), bottom=Side(border_style='thin'))

    # 第一列
    data_col_1_style = NamedStyle(name='data_col_1_style')
    data_col_1_style.font = Font(name='宋体', size='12')
    data_col_1_style.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    data_col_1_style.border = Border(left=Side(border_style='thin'), top=Side(border_style='thin'),
                                     right=Side(border_style='thin'), bottom=Side(border_style='thin'))

    # 第二列
    data_col_2_style = NamedStyle(name='data_col_2_style')
    data_col_2_style.font = Font(name='宋体', size='12')
    data_col_2_style.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    data_col_2_style.border = Border(left=Side(border_style='thin'), top=Side(border_style='thin'),
                                     right=Side(border_style='thin'), bottom=Side(border_style='thin'))

    # 第三列
    data_col_3_style = NamedStyle(name='data_col_3_style')
    data_col_3_style.font = Font(name='宋体', size='12')
    data_col_3_style.alignment = Alignment(horizontal='left', vertical='center', wrap_text=True)
    data_col_3_style.border = Border(left=Side(border_style='thin'), top=Side(border_style='thin'),
                                     right=Side(border_style='thin'), bottom=Side(border_style='thin'))

    # 案卷标题行
    data_bt_style = NamedStyle(name='data_bt_style')
    data_bt_style.font = Font(name='宋体', size='12')
    data_bt_style.alignment = Alignment(horizontal='center', vertical='center', wrap_text=True)
    data_bt_style.border = Border(left=Side(border_style='thin'), top=Side(border_style='thin'),
                                  right=Side(border_style='thin'), bottom=Side(border_style='thin'))

    # 空单元格样式
    empty_cell_style = NamedStyle(name='empty_cell_style')
    empty_cell_style.border = Border(left=Side(border_style='thin'), top=Side(border_style='thin'),
                                     right=Side(border_style='thin'), bottom=Side(border_style='thin'))

    # 第几页，共几页
    page_row19_style = NamedStyle(name='page_row19_style')
    page_row19_style.font = Font(name='宋体', size='12')
    page_row19_style.alignment = Alignment(horizontal='right', vertical='center', wrap_text=True)

    for each_sheet_name in wb.sheetnames:
        sheet = wb[each_sheet_name]
        # 设置页边距
        sheet.page_margins.left = 0.9
        sheet.page_margins.right = 0.3
        sheet.page_margins.top = 0.6
        sheet.page_margins.bottom = 0.45
        # 设置列宽
        sheet.column_dimensions['A'].width = 5.2
        sheet.column_dimensions['B'].width = 11.5
        sheet.column_dimensions['C'].width = 51
        sheet.column_dimensions['D'].width = 10
        sheet.column_dimensions['E'].width = 9.5
        sheet.column_dimensions['F'].width = 4.8
        sheet.column_dimensions['G'].width = 4.8
        # 单元格设置
        for i, row in enumerate(sheet.iter_rows(min_row=1, max_row=sheet.max_row, min_col=1, max_col=5)):
            row_num = i + 1  # 第几行
            page_row1 = ((row_num - 1) % 18) == 0
            page_row2 = ((row_num - 2) % 18) == 0
            page_row3 = ((row_num - 3) % 18) == 0
            page_row4 = ((row_num - 4) % 18) == 0
            for j, cell in enumerate(row):
                col_num = j + 1  # 第几列
                if cell.value is not None:
                    if page_row1:  # 卷内目录行
                        sheet.merge_cells(f"A{row_num}:E{row_num}")
                        sheet.row_dimensions[row_num].height = 32.25
                        cell.style = page_row1_style
                    elif page_row2:  # 档号行
                        sheet.merge_cells(f"A{row_num}:E{row_num}")
                        sheet.row_dimensions[row_num].height = 19.5
                        cell.style = page_row2_style
                    elif page_row3:  # 属性行
                        sheet.row_dimensions[row_num].height = 56.1
                        cell.style = page_row3_style
                    else:
                        sheet.row_dimensions[row_num].height = 43
                        if col_num == 1:
                            cell.style = data_col_1_style
                        elif col_num == 2:
                            cell.style = data_col_2_style
                            content_long = wcswidth(str(cell.value))
                            if 18 < content_long <= 31:
                                cell.font = Font(name='宋体', size='11')
                            elif 31 < content_long <= 39:
                                cell.font = Font(name='宋体', size='9')
                            elif 39 < content_long:
                                cell.font = Font(name='宋体', size='8')
                        elif col_num == 3:
                            cell.style = data_col_3_style
                            content_long = wcswidth(str(cell.value))
                            if 138 < content_long <= 149:
                                cell.font = Font(name='宋体', size='10')
                            elif 149 < content_long <= 167:
                                cell.font = Font(name='宋体', size='9')
                            elif 167 < content_long:
                                cell.font = Font(name='宋体', size='8')
                        elif col_num == 4:
                            cell.style = data_col_2_style
                        elif col_num == 5:
                            cell.style = data_col_2_style
                else:
                    cell.style = empty_cell_style

            if page_row4:  # 对案卷标题进行特殊处理
                if row[0].value is None and (row[2].value is not None) and (row[3].value is None):
                    row[2].style = data_bt_style
                    content_long = wcswidth(str(row[2].value))
                    if 136 < content_long <= 146:
                        row[2].font = Font(name='宋体', size='11')
                    elif 146 < content_long <= 160:
                        row[2].font = Font(name='宋体', size='10')
                    elif 160 < content_long <= 177:
                        row[2].font = Font(name='宋体', size='9')
                    elif 177 < content_long:
                        row[2].font = Font(name='宋体', size='8')

        wb.save(result_excel)


if __name__ == '__main__':
    # result = create_excels("../storage/excels/SWGS_中铁十四局集团有限公司（ZQ-2标）_中平跨京珠高速公路特大桥_案卷【1~20】卷内目录_164954", 500)
    result = create_excels(sys.argv[1], int(sys.argv[2]))
    print(result)
    if os.path.exists(sys.argv[1]):  # 删除源文件夹
        shutil.rmtree(sys.argv[1])
